<template>
  <div class="dict-type-page xl:pr-0!">
    <div class="dict-type-search">
      <a-input-search
        placeholder="请输入字典类型或名称搜索"
        v-model:value="searchInfo.name"
        @search="onSearch"
      />
    </div>
    <!-- 表格 -->
    <BasicTable
      @register="registerTable"
      :searchInfo="searchInfo"
      :rowSelection="{ type: 'radio', onChange: onSelectChange }"
    >
      <template #toolbar>
        <Authority value="sys:dict:type:save">
          <a-button-add @click="handleCreate" />
          <a-button-import import-code="sys:dict:type" />
        </Authority>
        <a-button-export
          :loading="exportBtnLoading"
          auth="sys:dict:type:select"
          @click="handelExportData"
        />
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="basic-table-action center">
            <a-button-edit small auth="sys:dict:type:save" :id="record.id" @click="handleEdit" />
            <a-divider type="vertical" />
            <a-button-remove
              small
              auth="sys:dict:type:remove"
              :id="record.id"
              :api="remove"
              @success="reload"
            />
          </div>
        </template>
      </template>
    </BasicTable>
    <!-- 表单 -->
    <SysDictTypeInput @register="registerModal" @success="reload" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue';
  import { BasicTable, useTable } from '@/components/Table';
  import { select, add, get, remove, exportData } from '@/api/sys/sysDictType';
  import { columns, searchFormSchema } from '@/views/sys/dict/type/dict-type.data';
  import SysDictTypeInput from '@/views/sys/dict/type/Input.vue';
  import {
    AButtonAdd,
    AButtonEdit,
    AButtonExport,
    AButtonImport,
    AButtonRemove,
  } from '@/components/Button';
  import { useModal } from '@/components/Modal';
  import { Authority } from '@/components/Authority';
  import { usePermission } from '@/hooks/web/usePermission';
  import { downloadFileById } from '@/utils/file/download';
  import { SysDictType } from '@/api/sys/model/sysDictTypeModel';

  export default defineComponent({
    name: 'SysDictTypeList',
    components: {
      AButtonImport,
      AButtonExport,
      Authority,
      AButtonRemove,
      AButtonEdit,
      SysDictTypeInput,
      AButtonAdd,
      BasicTable,
    },
    emits: ['change'],
    setup(_, { emit }) {
      // 表格选中数据
      const checkedKeys = ref<Array<string>>([]);
      // 导出按钮状态
      const exportBtnLoading = ref<boolean>(false);
      const { hasPermission } = usePermission();

      const searchInfo = reactive<Recordable>({
        name: '',
      });
      const name = ref();

      const [registerModal, { openModal }] = useModal();
      /**
       * 初始化表格
       */
      const [registerTable, { reload, getForm }] = useTable({
        title: '字典类型',
        api: select,
        columns,
        canResize: true,
        formConfig: {
          schemas: searchFormSchema,
        },
        useSearchForm: false,
        clickToRowSelect: true,
        showIndexColumn: false,
        pagination: {
          pageSize: 100,
        },
        showTableSetting: false,
        actionColumn: {
          ifShow() {
            return hasPermission('sys:dict:type:save');
          },
          width: 160,
          title: '操作',
          key: 'action',
        },
      });

      function handleCreate() {
        add().then((data) => {
          openModal(true, data);
        });
      }

      function handleEdit(id: string) {
        get(id).then((data) => {
          openModal(true, data);
        });
      }

      function onSearch() {
        reload();
      }

      const handelExportData = async () => {
        exportBtnLoading.value = true;
        try {
          await exportData(
            Object.assign(searchInfo, getForm().getFieldsValue()) as SysDictType,
          ).then((id) => {
            downloadFileById(id);
          });
        } catch (e) {
          console.error('导出数据错误', e);
        } finally {
          exportBtnLoading.value = false;
        }
      };

      return {
        name,
        checkedKeys,
        searchInfo,
        exportBtnLoading,
        onSelectChange(selectedRowKeys: string[], selectedRows: Recordable[]) {
          checkedKeys.value = selectedRowKeys;
          emit(
            'change',
            selectedRowKeys.length ? selectedRowKeys[0] : null,
            selectedRows.length ? selectedRows[0].type : null,
          );
        },
        remove,
        registerModal,
        registerTable,
        reload,
        handleCreate,
        handleEdit,
        onSearch,
        handelExportData,
      };
    },
  });
</script>
<style lang="less" scoped>
  .dict-type-page {
    padding: 16px;

    .dict-type-search {
      padding: 16px 16px 0;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      background-color: #fff;
    }

    :deep(.vben-basic-table) {
      .ant-table-wrapper {
        border-top-left-radius: 0;
        border-top-right-radius: 0;
      }
    }
  }
</style>
